package server;
/**
 * 启动服务器
 * @author sa
 * 2017年8月20日 19:58:50
 */
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.net.InetAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MachineServer {
	private static final Logger logger = Logger.getLogger(MachineServer.class.getName());
	private int port; 
	public MachineServer(int port)
	{
		this.port=port;
	}
	public void bind() throws Exception {
		// 配置服务端的NIO线程
		//EventLoopGroup线程组，专门处理网络事件，实际上就是Reactor线程
		EventLoopGroup bossGroup;  //用于服务端接收客户端的连
		EventLoopGroup workerGroup;//用于进行SocketChannel的网络读
		bossGroup = new NioEventLoopGroup();
		workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap sbsp = new ServerBootstrap();
			sbsp.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new ObjectDecoder(1024 * 1024,ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
							ch.pipeline().addLast(new ObjectEncoder());
							ch.pipeline().addLast(new server.MachineServerHandler());
						}
					});
			ChannelFuture f = sbsp.bind(port).sync();
			InetAddress addr = InetAddress.getLocalHost();
			logger.log(Level.INFO, "服务器已经启动，IP:"+addr.getHostAddress().toString()+"  端口: " + port);
			//服务器启动成功以后，开始监听客户端连接
			ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
			ClientMoniter cm=new ClientMoniter();
			service.scheduleAtFixedRate(cm,5,5,TimeUnit.SECONDS);

			f.channel().closeFuture().sync();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
	//	new MachineServer(8888).bind();
	}
}